package com.ruoyi.point.service.impl;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ISysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class OnlineServer {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserOnlineService userOnlineService;

    public int getOnline(String userName,String userId){
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        int i = 0;
        for (String key : keys)
        {
            LoginUser user = redisCache.getCacheObject(key);
            if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser()))
            {
                i = 1;
            } else if(StringUtils.isNotEmpty(userId) && StringUtils.isNotNull(user.getUserId())){
                i = 1;
            } else {
                i = 0;
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return i;
    }
}
